<?php
include('conf.php');
include('gridfs.class.php');
restore_error_handler();
$grid = $db->getGridFS('zq');//选择gridfs命名空间，默认是fs
$collections = new MongoCollection($db, 'zq.files');//指定一个mongo集合（类似mysql的一个表）

$dirparam = '';
empty($_GET['dir']) || $dirparam = trim($_GET['dir']);//获取当前目录

if(!empty($dirparam) && !preg_match('/^[\w\/]+\/$/',$dirparam)){
	exit('目录错误');
}

$zqObj = new zqGrid();
$reg_file = $zqObj->returnRegx('file',$dirparam);
$reg_dir = $zqObj->returnRegx('dir', $dirparam);
$dirList = $fileList = array();
$dirData = array();
$dirList = $collections->find(array('filename'=>$reg_dir))->sort(array('uploadDate'=>-1));//查找文件夹
$fileList = $collections->find(array('filename'=>$reg_file))->sort(array('uploadDate'=>-1));//查找文件

foreach($dirList as $k=>$val){
	if(!empty($dirparam)){
		$prereg = str_replace('/', '\/', $dirparam);//获取文件夹名称
		}else{
			$prereg = '';
			}
	
	preg_match('/^'.$prereg.'([^\f\n\r\t\v\/]+\/)/', $val['filename'],$resutl);
	$dirData[] = $resutl[1];
}
$dirData = array_unique($dirData);//去除重复的文件夹名称
foreach($fileList as $val){
	$fileData[] = $val;//文件列表
}

//上一级目录
$preDir = '';
if(!empty($dirparam)){
	preg_match('/[^\f\n\r\t\v\/]+\/$/', $dirparam, $preDir);
	if(!empty($preDir[0])){
		$preDir = $preDir[0];
		$preDir = str_replace($preDir, '', $dirparam);
	}
}


//文件上传
if(!empty($_FILES)){
	$current_dir = $_POST['current_dir'];
	$filename = $_FILES['file']['name'];
	if(!preg_match('/^[\S]+\.[\w]{1,4}$/',$filename)){
		$filename = 'file'.time().'.null';
	}
	$pathinfo = pathinfo($filename);
	//$_FILES['pic']['name'] = md5($filename).'.'.$pathinfo['extension'];
	$r = $grid->storeUpload('file', array('ext'=>$pathinfo['extension'],'timestamp'=>time()));//将文件上传至gridFS，返回一个Mongo的主键_id对象
		
	//更新文件名，文件上传好后将文件名更新成自定义的名称
	$newName =$current_dir.$filename;
	$newFileName = array('$set' => array("filename" => $newName));
	$where['_id'] = $r;
	$collections->update($where,$newFileName);
	header("Location:index.php?dir={$dirparam}");
}
//添加目录
if(empty($_FILES) && !empty($_POST)){
	if(!empty($_POST['dirname']) && preg_match('/^[\w]+$/i',$_POST['dirname'])){
		$current_dir = $_POST['current_dir'];
		$newfile = $current_dir.$_POST['dirname'].'/.';
		$r = $grid->storeFile('./current.file', array('other' => '当前目录'));
		
		$newFileName = array('$set' => array("filename" => $newfile));
		$where['_id'] = $r;
		$collections->update($where,$newFileName);
		header("Location:index.php?dir={$dirparam}");
	}else{
		exit('目录中不能包含特殊字符');
	}
}


//删除文件
if(!empty($_GET['del'])){
$delReg = str_replace(array('/','.'),array('\/','\.'),$_GET['del']);
$r = $grid->remove(array('filename'=>new MongoRegex("/^{$delReg}/") ));
header("Location:index.php?dir={$dirparam}");
}




?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>GRIDFS文件管理</title>
<link href="resource/css/css.css" rel="stylesheet" type="text/css" />
</head>

<body>

<div class="main center">
    	<h4><span><img src="resource/images/logo.png" width="16" height="39" /></span>GridFS一个简单的文件管理示例</h4>
  <div class="line"><div></div></div>
  <div class="formbox">
  	<form method="POST" >
    <strong>创建文件夹：</strong>
    <input  type="text"  name="dirname"/>
    <input type="hidden" name="current_dir" value="<?php echo $dirparam;?>" />
    <input type="submit" value="提交" />
    </form>
    
  	<form method="POST" enctype="multipart/form-data">
    <strong>上传文件：</strong>
    <input  type="file" name="file"/>
    <input type="hidden" name="current_dir" value="<?php echo $dirparam;?>" />
    <input type="submit" value="提交" />
    </form>
    
  <div class="clr"></div>
  </div>
  
  <div class="line"><div></div></div>
  <div>当前目录：/<?php echo  $dirparam;?></div>
  
  	<div class="filebox">
    	<?php if(!empty($dirparam)):?>
    	<div class="fileNode">
        	<a href="?dir=<?php echo $preDir; ?>" title="返回上层目录">
        	<div class="img"><img src="resource/images/icons/32/back.gif" /></div>
            <div>返回上层</div>
            </a>
        </div>
    	<?php endif;?>
        
    	<?php 
		if(!empty($dirData)):
		foreach($dirData as $val):
		?>
    	<div class="fileNode">
        	<div class="del"><a href="?dir=<?php echo $dirparam;?>&del=<?php echo $dirparam.$val;?>">X</a>&nbsp;</div>
        	<a href="?dir=<?php echo $dirparam.$val; ?>" title="<?php echo trim($val,'/');?>">
        	<div class="img"><img src="resource/images/icons/32/folder.gif" /></div>
            <div><?php echo str2dot(trim($val,'/'),6); ?></div>
            </a>
        </div>
        <?php endforeach;endif;?>
        
        <?php 
		if(!empty($fileData)):
		foreach($fileData as $val):?>
    	<div class="fileNode">
        	<div class="del"><a href="?dir=<?php echo $dirparam;?>&del=<?php echo $val['filename'];?>">X</a>&nbsp;</div>
   	    <a href="<?php echo $grid_nginx_url.$val['filename']; ?>" target='_blank' title="<?php echo str_replace($dirparam,'',$val['filename']); ?>">
        	<div class="img"><img src="resource/images/icons/32/<?php echo $val['ext']; ?>.gif" onerror="this.src='resource/images/icons/32/unknow.gif'" /></div>
            <div><?php echo str2dot(str_replace($dirparam,'',$val['filename']),6); ?></div>
            </a>
        </div>
         <?php endforeach;endif;?>
       
    
    <div class="clr"></div>
    </div>
</div>
</body>
</html>
<?php

//指定长度的字符串后面+上n个点
function str2dot ($str, $length) 
{
	if (mb_strlen($str, 'UTF-8') > $length) {
       $str = mb_substr($str, 0, $length, 'UTF-8');
       $str .= '...';
    }
    return $str;
}

?>
